import asyncio
from multiprocessing import SimpleQueue
import websockets.server
import logging
from worker import Worker
from config import WEBSOCKET_PORT


logger = logging.getLogger(__name__)


class Dispatcher(Worker):
    def __init__(self, buffer_commands: SimpleQueue) -> None:
        self._buffer_commands = buffer_commands

    async def _send_command(self, websocket: websockets.server.WebSocketServerProtocol) -> None:
        while True:
            command = self._buffer_commands.get()
            logger.info(f'Sending: {command}')
            await websocket.send(command)

    async def _run_forever(self) -> None:
        async with websockets.server.serve(self._send_command, 'localhost', WEBSOCKET_PORT):
            await asyncio.Future()

    def run_forever(self) -> None:
        asyncio.run(self._run_forever())
